lucky.define(['jquery', 'setter', 'artTemplate', 'modal', 'blockUI'],function(exports){
    var device = lucky.device(),
    modal = lucky.modal,
    setter = lucky.setter,

    APP_BODY = "AppContent",

    //构造器
    Class = function(id){
        this.id = id;
        this.container = $('#' + (id || APP_BODY));
    },
    //对外接口
    view = function(id){
        return new Class(id);
    };

    //显示加载进度条
    view.loading = {
        show: function (elem) {
            if(setter.debug){
                modal.load(undefined,{shadeClose:false});
            }
        },
        remove: function (elem) {
            if(setter.debug){
                modal.closeAll("loading");
            }
        }
    };

    view.error = function (content, options) {
        alert("错误："+ content);
    };

    //退出登录
    view.logout = function(){
        alert("退出登录");
    };

    //Ajax加载
    view.req = function (options) {
        var that = this
            , success = options.success
            , error = options.error
            , request = setter.request
            , response = setter.response
            , debug = function(){
            return setter.debug ? '<br><cite>URL：</cite>' + options.url : '';
        };

        options.data = options.data || {};
        options.headers = options.headers || {};

        if(request.tokenName){
            //自动给参数传入默认 token
            options.data[request.tokenName] = request.tokenName in options.data ? options.data[request.tokenName] : (lucky.data(setter.tableName)[request.tokenName] || '');

            //自动给 Request Headers 传入 token
            options.headers[request.tokenName] = request.tokenName in options.headers ? options.headers[request.tokenName] : (lucky.data(setter.tableName)[request.tokenName] || '');
        }

        delete options.success;
        delete options.error;

        // 传入options对象扩展jQuery原有的ajax方法
        var ajaxSettings = $.extend({
            type: 'get'
            , dataType: 'json'
            , success: function(res){
                var statusCode = response.statusCode;

                //只有 response 的 code 一切正常才执行 done
                if(res[response.statusName] == statusCode.ok) {
                    typeof options.done === 'function' && options.done(res);
                }
                //登录状态失效，清除本地 access_token，并强制跳转到登入页
                else if(res[response.statusName] == statusCode.logout){
                    view.logout();
                    return;
                }
                //其它异常
                else {
                    var error = ['<cite>Error：</cite> ' + (res[response.msgName] || '返回状态码异常'),debug()].join('');
                    //显示错误。。。
                    view.error(error);
                }

                typeof success === 'function' && success(res);
            }
            , error: function(ex, code){
                var error = ['请求异常，请重试<br><cite>错误信息：</cite>'+ code ,debug()].join('');
                //显示错误。。。
                view.error(error);

                typeof error === 'function' && error(res);
            }
        },options);

        return $.ajax(ajaxSettings);
    };

    //请求模板文件渲染
    Class.prototype.render = function (views, params) {
        var that = this
            , router = lucky.router();
        views = setter.views.path + views + setter.views.suffix;

        view.loading.show(that.container);

        var options = {
            url: views
            , type: 'get'
            , dataType: 'html'
            , data: {}
            , success: function(html){
                html = '<div>' + html + '</div>';

                var elemTitle = $(html).find('title')
                    , title = elemTitle.text() || (html.match(/\<title\>([\s\S]*)\<\/title>/)||[])[1];

                var res = {title: title, body:html};

                elemTitle.remove();
                that.params = params || {}; //获取参数

                // 请求成功执行回调
                if(that.then){
                    that.then(res);
                    delete that.then;
                }
                // 解析插入
                that.parse(html);
                view.loading.remove();

                // 解析成功执行回调
                if(that.done){
                    that.done(res);
                    delete that.done;
                }
            }
            , error: function(ex){
                view.loading.remove();

                // if(that.render.isError){
                //     that.render.isError = false;
                // 	return view.error('请求视图文件异常，状态：'+ ex.status);
                // }

                if(ex.status === 404){
                    that.render('common/error/404');
                }else{
                    that.render('common/error/error');
                }

                // that.render.isError = true;
            }
        };

        $.ajax(options);

        return that;
    };

    //解析模板
    Class.prototype.parse = function(html, refresh, callback){
        var that = this
            //是否模板元素
            , isScriptTpl = typeof html === 'object'
            , elem = isScriptTpl ? html : $(html)
            , elemTemp = isScriptTpl ? html : elem.find('*[template]')
            , fn = function(options){
                var renderResult = template.render(options.dataElem.html(),$.extend({params: router.params}, options.res));

                options.dataElem.after(renderResult);

                typeof callback === 'function' && callback();

                try {
                    options.done && new Function('d', options.done)(options.res);
                } catch(e){
                    console.error(options.dataElem[0], '\n存在错误回调脚本\n\n', e)
                }
            }
            , router = lucky.router();

        elem.find('title').remove();

        that.container[refresh ? 'after' : 'html'](elem.children());

        router.params = that.params || {};

        //遍历模板区块
        for(var i = elemTemp.length; i > 0; i--){
            (function(){
                var dataElem = elemTemp.eq(i - 1)
                    , artDone = dataElem.attr('art-done') || dataElem.attr('art-then') //获取回调
                    , url = (function(){
                        var artUrl = dataElem.attr('art-url') || '';
                        if($.trim(artUrl).length > 0){
                            artUrl = template.render(artUrl || '',router)
                        }
                        return artUrl;
                    }())
                    , data = (function(){
                    var artData = dataElem.attr('art-data') || '';
                    if($.trim(artData).length > 0){
                        artData = template.render(artData || '',router)
                    }
                    return artData;
                }()) //接口参数
                    , headers = (function(){
                    var artHeaders = dataElem.attr('art-headers') || '';
                    if($.trim(artHeaders).length > 0){
                        artHeaders = template.render(artHeaders || '',router)
                    }
                    return artHeaders;
                }()); //接口请求的头信息

                try {
                    data = new Function('return '+ data + ';')();
                } catch(e){
                    console.error('art-data: ' + e.message);
                    data = {};
                };

                try {
                    headers = new Function('return '+ headers + ';')();
                } catch(e){
                    console.error('art-headers: ' + e.message);
                    headers = headers || {}
                };

                if(url){
                    view.req({
                        type: dataElem.attr('art-type') || 'get'
                        , url: url
                        , data: data
                        , dataType: 'json'
                        , headers: headers
                        , success: function(res){
                            fn({dataElem: dataElem ,res: res ,done: artDone});
                        }
                    });
                } else {
                    fn({dataElem: dataElem, done: artDone});
                }

            }());
        }

        return that;
    };

    //直接渲染字符
    Class.prototype.send = function(views, data){
        var tpl = laytpl(views || this.container.html()).render(data || {});
        this.container.html(tpl);
        return this;
    };

    //局部刷新模板
    Class.prototype.refresh = function(callback){
        var that = this
            , next = that.container.next()
            , templateid = next.attr('templateid');

        if(that.id != templateid) return that;

        that.parse(that.container, 'refresh', function(){
            that.container.siblings('[templateid="'+ that.id +'"]:last').remove();
            typeof callback === 'function' && callback();
        });

        return that;
    };

    //视图请求成功后的回调
    Class.prototype.then = function(callback){
        this.then = callback;
        return this;
    };

    //视图渲染完毕后的回调
    Class.prototype.done = function(callback){
        this.done = callback;
        return this;
    };

    exports('view', view);
});